package fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.example.menhoo.toollibrary.android.log.Log;
import com.example.menhoo.toollibrary.common.helper.DateUtil;
import com.example.menhoo.toollibrary.common.utils.BitmapUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.example.menhoo.toollibrary.common.utils.StringUtil;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import adapter.ImAdapter;
import app.AutoFragment;
import app.im.IMAddChat;
import app.im.IMDetails2;
import app.im.details.IMDetailsActivity;
import app.Main;
import application.AppApplication;
import application.HttpUrlConstant;
import interfaces.IReturnObject;
import interfaces.ISignalrListener;
import mainUI.AppFragment;
import menhoo.com.i8officelibrary.R;
import model.AppModel;
import model.EmployeeItemDBModel;
import model.IMCvnDBModel;
import model.IMMessageDBModel;
import model.LoginUser;
import receiver.SignalrConnReceiver;
import tools.WeiXinTool;

/**
 * Created by yanglei on 15/9/17.
 */
public class IM2 extends AppFragment{
    public static boolean Is_Refresh=false;
    //选择人员
    public static final int Open_AddressBook = 0x1002;

    RecyclerView listView;

    ImageButton rightBtn;
    View layout;
    PopupWindow menuWindow;
    LinearLayout linearLayoutGoGroup,linearLayoutGoTalk,linearLayoutGoWeiXin,linearLayoutGoShouJi,linearLayoutIsShow;
    LinearLayout linearLayoutEmpty;
    Button buttonGoTalk;

    List<IMCvnDBModel> list = new ArrayList<>();
    ImAdapter adapter;
    WrapContentLinearLayoutManager layoutManager;

    String title;

    SignalrConnReceiver signalrConnReceiver;

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setRunSignalrService(true);
        super.onCreate(savedInstanceState);
        setContextView(R.layout.fragment_im);

        title = getTitle();
        setSignalreceiverHandle(new ISignalrListener() {
            @Override
            public void OnStart(Context context, Intent intent,String connID) {
                AppApplication.setSignalrID(connID);
                setTitle(title);
            }

            @Override
            public void OnStop(Context context, Intent intent) {
                //setTitle("未连接");
                setTitle("连接中...");
            }

            @Override
            public void OnRefreshOnline(Context context, Intent intent, String count) {

            }

            @Override
            public void HasUserOnline(Context context, Intent intent, JSONObject data) {

            }

            @Override
            public void HasUserOffline(Context context, Intent intent, JSONObject data) {

            }

            @Override
            public void OnMessage(Context context, Intent intent, JSONObject data) {
                if(adapter!=null && data!=null){
                    IMMessageDBModel model = new IMMessageDBModel(data);

                    IMCvnDBModel cvnDBModel = adapter.getItemByGroupID(model.GroupID);
                    if(cvnDBModel!=null){
                        if(cvnDBModel.type.toLowerCase().equalsIgnoreCase("group")){
                            if(model.MessageType.equalsIgnoreCase("Text")){
                                cvnDBModel.lastMessage=model.SenderName+":"+model.DecContext;
                            }
                            else{
                                cvnDBModel.lastMessage=model.SenderName+":"+"[文件]";
                            }

                        }
                        else{
                            if(model.MessageType.equalsIgnoreCase("Text")){
                                cvnDBModel.lastMessage=model.DecContext;
                            }
                            else{
                                cvnDBModel.lastMessage=model.SenderName+":"+"[文件]";
                            }

                        }
                        if(!model.SenderID.equalsIgnoreCase(AppApplication.getUser().EmplID)){
                            cvnDBModel.unreadCount+=1;
                        }

                        cvnDBModel.shortTime=model.ShortTime;

                        adapter.remove(cvnDBModel);

                        adapter.add(0,cvnDBModel);
                        linearLayoutEmpty.setVisibility(View.GONE);
                        try{
                            getDB().update(cvnDBModel);
                        }
                        catch (Exception ex){
                            LogUtils.e(ex.getMessage()+"");
                        }
                    }
                    else{
                        //本地没有这个会话就从网络上获取
                        requestDataById(model.GroupID, "group", new IReturnObject<IMCvnDBModel>() {
                            @Override
                            public void returnResult(IMCvnDBModel result) {
                                try{
                                    if(adapter!=null){
                                        adapter.add(0,result);
                                        linearLayoutEmpty.setVisibility(View.GONE);
                                    }
                                    getDB().save(result);
                                }
                                catch (Exception ex){
                                    LogUtils.e(ex.getMessage()+"");
                                }
                            }
                        });
                    }
                }
            }

            @Override
            public void HasCvnUpdate(Context context, Intent intent, JSONObject data) {
                if(adapter!=null){
                    try {
                        data = data.getJSONObject("Conversation");
                        String groupID = data.getString("groupID");
                        String id = data.getString("id");
                        String status = data.getString("status");
                        String name = data.getString("name");
                        String imgUrl = data.getString("imgUrl");
                        String lastMessage = data.getString("lastMessage");
                        String shortTime = data.getString("shortTime");
                        String type = data.getString("type");
                        int userCount = data.getInt("userCount");
                        String partnerUser = data.getString("partnerUser");
                        String draft = data.getString("draft");
                        int unreadCount = data.getInt("unreadCount");
                        String messagesInWnd = data.getString("messagesInWnd");
                        String scrollOffsetOfWnd = data.getString("scrollOffsetOfWnd");
                        String createTime = data.getString("createTime");
                        long timeStamp = data.getLong("timeStamp");

                        IMCvnDBModel model = new IMCvnDBModel();
                        model.groupID = groupID;
                        model.id = id;
                        model.status = status;
                        model.name = name;
                        model.imgUrl = imgUrl;
                        model.lastMessage = lastMessage;
                        model.shortTime = shortTime;
                        model.type = type;
                        model.userCount = userCount;
                        model.partnerUser = partnerUser;
                        model.draft = draft;
                        model.unreadCount = unreadCount;
                        model.messagesInWnd = messagesInWnd;
                        model.scrollOffsetOfWnd = scrollOffsetOfWnd;
                        model.createTime = DateUtil.StringToDate(createTime);
                        model.lastTime = new Date(timeStamp*1000);
                        model.CurrUserID=AppApplication.getUser().EmplID;
                        model.CurrWebSite=HttpUrlConstant.getWebSiteFullUrl("");

                        adapter.update(model);
                    }
                    catch (Exception ex){
                        LogUtils.e(ex.getMessage()+"");

                    }
//                    MessageUtil.showShortToast(context,data.toString());
                }
            }
        });
        signalrConnReceiver = new SignalrConnReceiver() {
            @Override
            public void SignalrConnHandle(Context context, Intent intent) {
                setTitle(title);
            }

            @Override
            public void SignalrStopHandle(Context context, Intent intent) {
                setTitle("连接中...");
            }
        };


    }

    public void refreshIMTip(){
        try {
            List<IMCvnDBModel> cvnList = getDB().findAll(Selector.from(IMCvnDBModel.class).where("unreadCount",">",0).and("CurrUserID","=",AppApplication
                    .getUser().EmplID).and("CurrWebSite","=", HttpUrlConstant.getWebSiteFullUrl("")));
            if(cvnList!=null && cvnList.size()>0){
                int i=0;
                for(IMCvnDBModel item : cvnList){
                    i+=item.unreadCount;
                }
                if(i>99){
                    ((Main) getActivity()).showTip(getTitle(), "99+");
                }
                else{
                    ((Main) getActivity()).showTip(getTitle(), i+"");
                }
            }
            else{
                ((Main) getActivity()).hideTip(getTitle());
            }
        }
        catch (Exception e){}
    }

    @Override
    public void init() {
        super.init();
        try{
            ((Main) getActivity()).setIMTipType(getTitle());
        }
        catch (Exception e){}
        //
        try{
            listView = (RecyclerView)rootView.findViewById(R.id.listView);
        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }

        linearLayoutEmpty=(LinearLayout) rootView.findViewById(R.id.linearLayoutEmpty);
        buttonGoTalk = (Button) rootView.findViewById(R.id.buttonGoTalk);
        buttonGoTalk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuWindow.showAsDropDown(rightBtn);
            }
        });

        setCustomRightButton(R.layout.fragment_im_right_btn);
        rightBtn = (ImageButton)rootView.findViewById(R.id.rightBtn);
        rightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuWindow.showAsDropDown(v);
//                Intent it = new Intent(getActivity(), IMAddChat.class);
//                it.putExtra("deptID", "0");
//                it.putExtra("title", "创建聊天");
//                startActivity(it);
            }
        });
        //
        layout=inflater.inflate(R.layout.fragment_im_popup, null);
        menuWindow = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); //后两个参数是width和height
        menuWindow.setFocusable(true);
        menuWindow.setOutsideTouchable(true);
        menuWindow.update();
        menuWindow.setBackgroundDrawable(new BitmapDrawable());

        //linearLayoutIsShow
        linearLayoutGoGroup = (LinearLayout) layout.findViewById(R.id.linearLayoutGoGroup);
        linearLayoutGoTalk = (LinearLayout) layout.findViewById(R.id.linearLayoutGoTalk);
        linearLayoutGoWeiXin = (LinearLayout) layout.findViewById(R.id.linearLayoutGoWeiXin);
        linearLayoutGoShouJi = (LinearLayout) layout.findViewById(R.id.linearLayoutGoShouJi);
        linearLayoutIsShow = (LinearLayout) layout.findViewById(R.id.linearLayoutIsShow);

        if(!AppApplication.getUser().CanInvite){
            linearLayoutIsShow.setVisibility(View.GONE);
        }

        linearLayoutGoGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AppModel appModel = new AppModel();
                appModel.code="People";
                appModel.type="internal";
                appModel.name = "通讯录";

                Bundle bundle = new Bundle();
                bundle.putBoolean("IsMultiple", true);
                bundle.putString("HideEmplIDList", AppApplication.getUser().EmplID);

                Intent it =new Intent(context, AutoFragment.class);
                it.putExtra("Model",appModel);
                it.putExtra("IsReturnResult",true);
                it.putExtra("TagBundle",bundle);
                startActivityForResult(it, Open_AddressBook);
                menuWindow.dismiss();
            }
        });
        linearLayoutGoTalk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AppModel appModel = new AppModel();
                appModel.code="People";
                appModel.type="internal";
                appModel.name = "通讯录";

                Bundle bundle = new Bundle();
                bundle.putBoolean("IsMultiple", false);

                Intent it =new Intent(context, AutoFragment.class);
                it.putExtra("Model",appModel);
                it.putExtra("IsReturnResult",true);
                it.putExtra("TagBundle",bundle);
                startActivityForResult(it, Open_AddressBook);
                menuWindow.dismiss();
            }
        });

        linearLayoutGoWeiXin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                RequestParams params = new RequestParams();
                params.addQueryStringParameter("__session__", AppApplication.getSession());
                HttpSend(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.DoReg),
                        params, new RequestCallBack<String>() {
                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                String result = responseInfo.result;
                                if (result != null) {
                                    try
                                    {
                                        JSONObject jsonObject = new JSONObject(result);
                                        if (jsonObject.getBoolean("Succeed")) {
                                            String TokenID = jsonObject.getString("TokenID");
                                            LoginUser user = AppApplication.getUser();
                                            String title = user.EmplName+", 邀请您加入团队";

                                            String url = HttpUrlConstant.getWebSiteFullUrl(user.InviteWechatUrl+TokenID);
                                            String desc = "移动办公少不了你，同事们都在这里，赶快加入吧。";
                                            Bitmap thumb = BitmapUtil.getRoundedCornerBitmap(BitmapFactory.decodeStream(context.getResources()
                                                    .openRawResource(R.raw.ic_launcher)), 15f);
                                            WeiXinTool.html(title,thumb,url,desc);
                                        }


                                    } catch (Exception e) {
                                        LogUtils.e(e.getMessage() + "");
                                    }
                                }
                            }

                            @Override
                            public void onFailure(HttpException error, String msg) {
                            }
                        });
                menuWindow.dismiss();
            }
        });
        linearLayoutGoShouJi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginUser user = AppApplication.getUser();
                AppModel appModel = new AppModel();
                appModel.code="html";
                appModel.htmlUrl=user.InvitePhoneUrl;
                appModel.name = "通过手机号邀请";

                Intent it =new Intent(context, AutoFragment.class);
                it.putExtra("Model",appModel);
                startActivity(it);
                menuWindow.dismiss();
            }
        });

        adapter = new ImAdapter(context);
        adapter.setOnItemClickLitener(new ImAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                try{
                    IMCvnDBModel item =adapter.getItem(position);
                    item.unreadCount=0;
                    getDB().update(item);
                    adapter.notifyDataSetChanged();
                    //confirmMsg(item.groupID);

                    Intent it =new Intent(context, IMDetailsActivity.class);
                    it.putExtra("Title",item.name);
                    it.putExtra("UnreadCount",item.unreadCount);
                    it.putExtra("UserCount",item.userCount);
                    it.putExtra("GroupID",item.groupID);
                    it.putExtra("Type",item.type);
                    it.putExtra("ID",item.id);
                    startActivity(it);
                }
                catch (Exception ex){}
            }

            @Override
            public void onItemLongClick(View view, int position) {
                try{
                    final IMCvnDBModel item = adapter.getItem(position);
                    final android.app.Dialog dialog = getAppActivity().showSimpleCustomDialogMessage(R.layout.im_cnv_dialog,true);
                    if(dialog!=null){
                        com.rey.material.widget.Button buttonRead =(com.rey.material.widget.Button)dialog.findViewById(R.id.buttonRead);
                        buttonRead.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                confirmMsg(item.groupID);

                                dialog.dismiss();
                            }
                        });

                        com.rey.material.widget.Button buttonDel =(com.rey.material.widget.Button)dialog.findViewById(R.id.buttonDel);
                        buttonDel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                deleteConversationById(item.groupID);
                                try{
                                    getDB().deleteById(IMCvnDBModel.class,item.groupID);
                                    List<IMMessageDBModel> list = getDB().findAll(Selector.from(IMMessageDBModel.class).where("GroupID","=",item.groupID));
                                    getDB().deleteAll(list);

                                    long count = getDB().count(IMCvnDBModel.class);
                                    if(count>0){
                                        linearLayoutEmpty.setVisibility(View.GONE);
                                    }
                                    else{
                                        linearLayoutEmpty.setVisibility(View.VISIBLE);
                                    }

                                    refreshIMTip();

                                }
                                catch (Exception e){
                                    LogUtils.e(e.getMessage()+"");
                                }
                                dialog.dismiss();
                            }
                        });


                    }
                }
                catch (Exception ex){}
            }
        });

        layoutManager =new WrapContentLinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        layoutManager.setReverseLayout(false);
        layoutManager.setSmoothScrollbarEnabled(true);
        listView.setLayoutManager(layoutManager);
        listView.getItemAnimator().setChangeDuration(0);
        listView.setAdapter(adapter);

        firstDataInit();
    }

    public void firstDataInit(){
        Is_Refresh=false;
        adapter.clear();
        //先看看数据库中有无数据
        try {
            List<IMCvnDBModel> list = getDB().findAll(Selector.from(IMCvnDBModel.class).where("CurrUserID","=", AppApplication
                    .getUser().EmplID).and("CurrWebSite","=",HttpUrlConstant.getWebSiteFullUrl("")).orderBy("lastTime",true));
            if(list!=null && list.size()>0){
                linearLayoutEmpty.setVisibility(View.GONE);
                listView.setAdapter(adapter);
                adapter.add(list);
            }
            else{
                linearLayoutEmpty.setVisibility(View.VISIBLE);
            }
        }
        catch (Exception ex){
            LogUtils.e(ex.getMessage()+"");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(Is_Refresh){
            firstDataInit();
        }
        else{
            requestData();
        }

        //注册
        context.registerReceiver(signalrConnReceiver,new IntentFilter(signalrConnReceiver.Action));
    }

    @Override
    public void onPause() {
        super.onPause();
        //解除
        if(signalrConnReceiver!=null){
            context.unregisterReceiver(signalrConnReceiver);
        }
    }

    /**
     * 请求会话数据
     */
    private void requestData(){
//        setTitle("获取中...");
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        LogUtils.e("IM:"+HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.GetConversationList));
        LogUtils.e("IM:"+AppApplication.getSession());
        HttpSend(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.GetConversationList),
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.e("获取群聊信息" , result);
                        if (result != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    list = new ArrayList();

                                    JSONArray appArray = jsonObject.getJSONArray("Data");
                                    for (int i = 0; i < appArray.length(); i++) {
                                        JSONObject appJson = appArray.getJSONObject(i);
                                        String groupID = appJson.getString("groupID");
                                        String id = appJson.getString("id");
                                        String status = appJson.getString("status");
                                        String name = appJson.getString("name");
                                        String imgUrl = appJson.getString("imgUrl");
                                        String lastMessage = appJson.getString("lastMessage");
                                        String shortTime = appJson.getString("shortTime");
                                        String type = appJson.getString("type");
                                        int userCount = appJson.getInt("userCount");
                                        String partnerUser = appJson.getString("partnerUser");
                                        String draft = appJson.getString("draft");
                                        int unreadCount = appJson.getInt("unreadCount");
                                        String messagesInWnd = appJson.getString("messagesInWnd");
                                        String scrollOffsetOfWnd = appJson.getString("scrollOffsetOfWnd");
                                        String createTime = appJson.getString("createTime");
                                        long timeStamp = appJson.getLong("timeStamp");
                                        //
                                        IMCvnDBModel model = new IMCvnDBModel();
                                        model.groupID = groupID;
                                        model.id = id;
                                        model.status = status;
                                        model.name = name;
                                        model.imgUrl = imgUrl;
                                        model.lastMessage = lastMessage;
                                        model.shortTime = shortTime;
                                        model.type = type;
                                        model.userCount = userCount;
                                        model.partnerUser = partnerUser;
                                        model.draft = draft;
                                        model.unreadCount = unreadCount;
                                        model.messagesInWnd = messagesInWnd;
                                        model.scrollOffsetOfWnd = scrollOffsetOfWnd;
                                        model.createTime = DateUtil.StringToDate(createTime);
                                        model.lastTime = new Date(timeStamp*1000);
                                        model.CurrUserID=AppApplication.getUser().EmplID;
                                        model.CurrWebSite=HttpUrlConstant.getWebSiteFullUrl("");

                                        list.add(model);
                                    }
                                    if(adapter!=null){
                                        if(list!=null && list.size()>0){
                                            linearLayoutEmpty.setVisibility(View.GONE);
//                                            adapter.clear();
//                                            adapter.add(list);
                                            adapter.refresh(list);
                                            try {
                                                getDB().deleteAll(IMCvnDBModel.class);
                                                getDB().saveAll(list);
                                            }
                                            catch (Exception ex){
                                                LogUtils.e(ex.getMessage()+"");
                                            }
                                        }

                                    }
//                                    else{
//                                        if(list!=null && list.size()>0){
//                                            linearLayoutEmpty.setVisibility(View.GONE);
//                                            adapter.update(list);
//                                            for(IMCvnDBModel item : list){
//                                                try{
//                                                    long count = getDB().count(Selector.from(IMCvnDBModel.class).where("groupID","=",item.groupID));
//                                                    if(count>0){
//                                                        getDB().update(item);
//                                                    }
//                                                    else{
//                                                        getDB().save(item);
//                                                    }
//                                                }
//                                                catch (Exception ex){
//                                                    LogUtils.e(ex.getMessage()+"");
//                                                }
//                                            }
//                                        }
//                                    }

                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
//                        setTitle(title);
                        refreshIMTip();
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
//                        setTitle(title);
                    }
                });

    }
    private void requestDataById(final String id, final String type, final IReturnObject<IMCvnDBModel> returnObj){
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("type", type);
        params.addQueryStringParameter("isFullMessage", "false");

        HttpSend(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.GetConversationById),
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        if (result != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {

                                    JSONObject appJson = jsonObject.getJSONObject("Data").getJSONObject("Conversation");
                                    //
                                    String groupID = appJson.getString("groupID");
                                    String id = appJson.getString("id");
                                    String status = appJson.getString("status");
                                    String name = appJson.getString("name");
                                    String imgUrl = appJson.getString("imgUrl");
                                    String lastMessage = appJson.getString("lastMessage");
                                    String shortTime = appJson.getString("shortTime");
                                    String type = appJson.getString("type");
                                    int userCount = appJson.getInt("userCount");
                                    String partnerUser = appJson.getString("partnerUser");
                                    String draft = appJson.getString("draft");
                                    int unreadCount = appJson.getInt("unreadCount");
                                    String messagesInWnd = appJson.getString("messagesInWnd");
                                    String scrollOffsetOfWnd = appJson.getString("scrollOffsetOfWnd");
                                    //
                                    IMCvnDBModel model = new IMCvnDBModel();
                                    model.groupID = groupID;
                                    model.id = id;
                                    model.status = status;
                                    model.name = name;
                                    model.imgUrl = imgUrl;
                                    model.lastMessage = lastMessage;
                                    model.shortTime = shortTime;
                                    model.type = type;
                                    model.userCount = userCount;
                                    model.partnerUser = partnerUser;
                                    model.draft = draft;
                                    model.unreadCount = unreadCount;
                                    model.messagesInWnd = messagesInWnd;
                                    model.scrollOffsetOfWnd = scrollOffsetOfWnd;
                                    model.CurrUserID=AppApplication.getUser().EmplID;
                                    model.CurrWebSite=HttpUrlConstant.getWebSiteFullUrl("");

                                    returnObj.returnResult(model);
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });

    }
    private void confirmMsg(final String groupID){
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("groupID", groupID);

        HttpSend(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.ConfirmMsg),
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        if (result != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    if(adapter!=null){
                                        IMCvnDBModel item =adapter.getItemByGroupID(groupID);
                                        if(item!=null){
                                            item.unreadCount=0;
                                            adapter.notifyDataSetChanged();
                                            getDB().update(item);
                                            refreshIMTip();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });

    }
    private void deleteConversationById(final String groupID){
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("groupID", groupID);

        HttpSend(HttpMethod.POST, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.DeleteConversationById),
                params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        if (result != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getBoolean("Succeed")) {
                                    if(adapter!=null){
                                        IMCvnDBModel item =adapter.getItemByGroupID(groupID);
                                        if(item!=null){
                                            adapter.getData().remove(item);
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                    }
                });

    }
    /**
     * 创建群组
     */
    private void createGroup(String emplIdList){
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("groupName", "群聊");
        params.addQueryStringParameter("groupDesc", "");
        params.addQueryStringParameter("emplIdList", emplIdList);

        Post(HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.CreateGroupConversation), params, new IReturnObject<String>() {
            @Override
            public void returnResult(String result) {
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getBoolean("Succeed")) {

                            JSONObject appJson = jsonObject.getJSONObject("Data");
                            String groupID = appJson.getString("groupID");
                            String id = appJson.getString("id");
                            String status = appJson.getString("status");
                            String name = appJson.getString("name");
                            String imgUrl = appJson.getString("imgUrl");
                            String lastMessage = appJson.getString("lastMessage");
                            String shortTime = appJson.getString("shortTime");
                            String type = appJson.getString("type");
                            int userCount = appJson.getInt("userCount");
                            String partnerUser = appJson.getString("partnerUser");
                            String draft = appJson.getString("draft");
                            int unreadCount = appJson.getInt("unreadCount");
                            String messagesInWnd = appJson.getString("messagesInWnd");
                            String scrollOffsetOfWnd = appJson.getString("scrollOffsetOfWnd");
                            String createTime = appJson.getString("createTime");
                            long timeStamp = appJson.getLong("timeStamp");

                            IMCvnDBModel model = new IMCvnDBModel();
                            model.groupID = groupID;
                            model.id = id;
                            model.status = status;
                            model.name = name;
                            model.imgUrl = imgUrl;
                            model.lastMessage = lastMessage;
                            model.shortTime = shortTime;
                            model.type = type;
                            model.userCount = userCount;
                            model.partnerUser = partnerUser;
                            model.draft = draft;
                            model.unreadCount = unreadCount;
                            model.messagesInWnd = messagesInWnd;
                            model.scrollOffsetOfWnd = scrollOffsetOfWnd;
                            model.createTime = DateUtil.StringToDate(createTime);
                            model.lastTime = new Date(timeStamp*1000);
                            model.CurrUserID=AppApplication.getUser().EmplID;
                            model.CurrWebSite=HttpUrlConstant.getWebSiteFullUrl("");

                            list.add(model);

                            adapter.add(0,model);
                            linearLayoutEmpty.setVisibility(View.GONE);
                            try {
                                getDB().save(model);
                            }
                            catch (Exception ex){
                                LogUtils.e(ex.getMessage()+"");
                            }
                        }
                    } catch (Exception ex) {
                        LogUtils.e(ex.getMessage() + "");
                    }
                }

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode== Activity.RESULT_OK && requestCode==Open_AddressBook){
            try{
                final ArrayList<EmployeeItemDBModel> list1 = (ArrayList<EmployeeItemDBModel>)data.getSerializableExtra("Data");
                boolean IsMultiple = data.getBooleanExtra("IsMultiple",true);
                if(list1!=null && list1.size()>0){

                    //MessageUtil.showShortToast(context,"result::"+list.size());
                    if(list1.size()>1){
                        HandlerUtil.runOnUiThreadDelay(new Runnable() {
                            @Override
                            public void run() {
                                ArrayList<String> list2 = new ArrayList<>();
                                for(EmployeeItemDBModel item : list1){
                                    list2.add(item.EmplID);
                                }
                                createGroup(AppApplication.getUser().EmplID+","+ StringUtil.join(list2,","));
                            }
                        },500);

                    }
                    else{
                        HandlerUtil.runOnUiThreadDelay(new Runnable() {
                            @Override
                            public void run() {
                                requestDataById(list1.get(0).EmplID, "couple", new IReturnObject<IMCvnDBModel>() {
                                    @Override
                                    public void returnResult(IMCvnDBModel result) {
                                        list.add(result);

                                        adapter.add(0,result);
                                        linearLayoutEmpty.setVisibility(View.GONE);
                                        try {
                                            getDB().save(result);
                                        }
                                        catch (Exception ex){
                                            LogUtils.e(ex.getMessage()+"");
                                        }

                                    }
                                });
                            }
                        },500);

                    }

                }
            }
            catch (Exception e){
                LogUtils.e(e.getMessage()+"");
            }

        }
    }

    public class WrapContentLinearLayoutManager extends LinearLayoutManager {
        public WrapContentLinearLayoutManager(Context context) {
            super(context);
        }

        public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }

        public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }
}
